package com.hbpu.maven.spring.tx.dao;

import com.hbpu.maven.spring.tx.bean.Book;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class BookDao {

    @Autowired
    JdbcTemplate jdbcTemplate;

    public Book selectBookById(Integer id) {

        String sql = "select * from book where id = ?";

        List<Book> query = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(Book.class), id);

        return query.get(0);
    }

    public void insertBook(Book book) {
        String sql = "insert into book values(default,?,?,?)";
        int update = jdbcTemplate.update(sql, book.getBookname(), book.getPrice(), book.getStock());
        if (update != 1) {
            System.out.println("插入失败！");
        } else {
            System.out.println("插入成功！");
        }
    }

    public void deleteBookById(Integer id) {
        String sql = "delete from book where id = ?";
        int update = jdbcTemplate.update(sql, id);
        if (update != 1) {
            System.out.println("删除失败！");
        } else {
            System.out.println("删除成功！");
        }
    }

    public void updateBookStock(Integer id,Integer number) {
        String sql = "update book set stock = stock - ? where id = ?";

        int update = jdbcTemplate.update(sql, number, id);
    }
}
